package com.itaem.community.core.advice;

import com.itaem.community.core.entity.Result;
import com.itaem.community.core.exception.CommunityException;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

import static com.itaem.community.core.enums.ResultEnum.ERROR;

/**
 * <p>项目名称: community </p>
 * <p>文件名称: ResponseAdvice </p>
 * <p>描述: [类型描述] </p>
 * <p>创建时间: 2020/10/13 </p>
 * <p>作者信息: tomato</p>
 *
 * @author tomato
 * @version v1.0
 */
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(CommunityException.class)
    public Result communityExceptionHandler(CommunityException e) {
        log.error(e.getMessage(), e.getCause());
        if (StringUtils.isNotBlank(e.getMessage())) {
            return Result.failure(ERROR).setMessage(e.getMessage());
        }
        return Result.failure(ERROR);
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result duplicateKeyExceptionHandler(DuplicateKeyException dke) {
        log.error(dke.getMessage(), dke.getCause());
        return Result.failure(ERROR).setMessage("请不要重复添加!");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result notValidExceptionHandler(MethodArgumentNotValidException nanve) {
        log.warn(nanve.getMessage(), nanve.getCause());
        return Result.failure(ERROR, extractAllValidationExceptionMessage(nanve)).setMessage("非法参数");
    }

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        log.error(e.getMessage(), e.getCause());
        return Result.failure(ERROR);
    }

    private List<String> extractAllValidationExceptionMessage(MethodArgumentNotValidException nanve) {
        return nanve
                .getBindingResult()
                .getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
    }
}
